package server

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/godruoyi/go-snowflake"
	"github.com/jinzhu/copier"
	"github.com/spf13/cast"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
	global2 "longmen/server/config/global"
	fans_group2 "longmen/server/internal/rpc/tencentim/fans_group"
	"longmen/server/internal/rpc/tencentim/fans_group/fans_messages"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/common/api_models"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/services"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"sort"
	"strconv"
	"time"
)

/**
==================================后台接口============================================================================
*/

// 创建群聊
func (s *TencentIM) CreateGroupChat(ctx context.Context, req *pb.CreateGroupChatReq) (resp *pb.CreateGroupChatResp, err error) {
	resp = &pb.CreateGroupChatResp{
		IsSucceed:   false,
		Tips:        "",
		GroupChatId: 0,
	}

	groups, err := db_main.GetGroupChatList(map[string]interface{}{
		"anchor_id": req.AnchorId,
	}, "", 0, 0)
	if err != nil {
		resp.Tips = "内部错误"
		return resp, status.Error(codes.Internal, "内部错误")
	}

	if len(groups) >= 10 {
		resp.Tips = "群数量达上限"
		return resp, status.Error(codes.Internal, "群数量达上限")
	}

	groupChat := &models_main.GroupChat{
		CreatedAt:     time.Now(),
		FansGroupId:   "",
		Name:          req.Name,
		Avatar:        req.Avatar,
		Introduce:     req.Introduce,
		WelcomeDesc:   req.WelcomeDesc,
		AnchorId:      int(req.AnchorId),
		CreateAdminId: int(req.CreateAdminId),
		Status:        models_main.GroupChatStatusNormal,
		UserNum:       1,
	}

	var fansGroupId string
	err = global2.GetX().Transaction(func(tx *gorm.DB) error {
		err = db_main.InsertGroupChatTx(tx, groupChat)
		if err != nil {
			return err
		}

		fansGroupId = fmt.Sprintf("%d_%d", groupChat.AnchorId, groupChat.Id)
		ok := imsdk2.GetSdk().CreateFansGroup(imsdk2.CreateFansGroupRequest{
			OwnerAccount: "admin",     // 群管理员
			GroupID:      fansGroupId, // 群ID，需要生成规则并保存到表里
			Name: func() string {
				r := []rune(req.Name)
				if len(r) > 10 {
					r = r[:10]
				}
				return string(r)
			}(), // 群名称
		})
		if !ok {
			return errors.New("im建群失败")
		}
		return nil
	})
	if err != nil {
		resp.Tips = "创建群失败"
		return resp, status.Error(codes.Internal, err.Error())
	}

	groupChat.FansGroupId = fansGroupId
	err = db_main.UpdateGroupChat([]string{"fans_group_id"}, groupChat)
	if err != nil {
		resp.Tips = "内部错误"
		return resp, status.Error(codes.Internal, "内部错误")
	}
	cache.DelFansGroup(groupChat.Id)

	user, _ := mysql.GetUserParam(map[string]interface{}{
		"id": req.AnchorId,
	})
	groupChatUser := &models_main.GroupChatUser{
		CreatedAt:   time.Now(),
		GroupId:     groupChat.Id,
		FansGroupId: fansGroupId,
		UserId:      int(req.AnchorId),
		Role:        models_main.GroupChatRoleMaster,
		Status:      models_main.GroupChatUserStatusCommon,
	}
	err = db_main.InsertGroupChatUser(groupChatUser)
	if err != nil {
		resp.Tips = "内部错误"
		return resp, status.Error(codes.Internal, "内部错误")
	}

	for {
		retryNum := false
	AddGroup:
		ok, res := imsdk2.GetSdk().AddGroupMember(imsdk2.AddGroupMemberRequest{
			GroupId: fansGroupId,
			Silence: 1,
			MemberList: []imsdk2.MemberList{
				{
					MemberAccount: cast.ToString(req.AnchorId),
				},
			},
		})
		if retryNum {
			break
		}
		if !ok {
			//账号未登录
			if res.ErrorCode == 10019 {
				ok = imsdk2.GetSdk().CreateAccount(imsdk2.CreateAccountRequest{
					UserID:  cast.ToString(req.AnchorId),
					Nick:    user.NickName,
					FaceURL: user.Avatar,
				})
				if ok {
					retryNum = true
					goto AddGroup
				}
			}
		}
		break
	}

	resp = &pb.CreateGroupChatResp{
		IsSucceed:   true,
		Tips:        "ok",
		GroupChatId: uint32(groupChat.Id),
	}

	return
}

// 解散群聊
func (s *TencentIM) DissolveGroupChat(ctx context.Context, req *pb.DissolveGroupChatReq) (resp *pb.DissolveGroupChatResp, err error) {
	resp = &pb.DissolveGroupChatResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}
	if groupChat.Status != models_main.GroupChatStatusNormal {
		err = errors.New("群组已解散")
		resp.Tips = err.Error()
		return
	}
	groupChat.Status = models_main.GroupChatStatusDissolve

	err = db_main.UpdateGroupChat([]string{"status"}, groupChat)
	if err != nil {
		resp.Tips = err.Error()
		return resp, status.Error(codes.Internal, "解散群聊失败")
	}
	cache.DelFansGroup(groupChat.Id)

	err = imsdk2.GetSdk().DestroyGroup(groupChat.FansGroupId)
	if err != nil {
		resp.Tips = err.Error()
		return resp, status.Error(codes.Internal, fmt.Errorf(" 删除群失败: %v", err).Error())
	}

	cache.DelFansGroup(groupChat.FansGroupId)

	resp = &pb.DissolveGroupChatResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 设置房管
func (s *TencentIM) AssignGroupChatAdmin(ctx context.Context, req *pb.AssignGroupChatAdminReq) (resp *pb.AssignGroupChatAdminResp, err error) {
	resp = &pb.AssignGroupChatAdminResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"group_id": req.GroupChatId,
		"user_id":  req.UserId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		err = fmt.Errorf("群成员id%d不存在", req.UserId)
		resp.Tips = err.Error()
		return
	}

	if gcUser.Role != models_main.GroupChatRoleMember {
		err = fmt.Errorf("非普通成员不能设置为房管")
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatUserRole(int(req.UserId), models_main.GroupChatRoleAdmin)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.AssignGroupChatAdminResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 取消房管
func (s *TencentIM) CancelAssignGroupChatAdmin(ctx context.Context, req *pb.CancelAssignGroupChatAdminReq) (resp *pb.CancelAssignGroupChatAdminResp, err error) {
	resp = &pb.CancelAssignGroupChatAdminResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"group_id": req.GroupChatId,
		"user_id":  req.UserId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		err = fmt.Errorf("群成员id%d不存在", req.UserId)
		resp.Tips = err.Error()
		return
	}

	if gcUser.Role != models_main.GroupChatRoleAdmin {
		err = fmt.Errorf("当前用户非房管")
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatUserRole(int(req.UserId), models_main.GroupChatRoleMember)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.CancelAssignGroupChatAdminResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 删除消息
func (s *TencentIM) DeleteMessage(ctx context.Context, req *pb.DeleteMessageReq) (resp *pb.DeleteMessageResp, err error) {
	resp = &pb.DeleteMessageResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	h, err := fans_group2.GetFromEs(req.MsgId)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	users, _ := db_main.GetUsersParam(map[string]interface{}{
		"id": map[string]interface{}{
			"in": []int{int(req.MgrId), h.Uid},
		},
	}, "", 0, 0)
	userMp := map[int]models_main.User{}
	for k, v := range users {
		userMp[v.Id] = *users[k]
	}
	mgr, _ := userMp[int(req.MgrId)]
	user, _ := userMp[h.Uid]

	type DeleteContent struct {
		IsBackend    bool   `json:"is_backend"`
		AdminId      int    `json:"admin_id"`
		AdminName    string `json:"admin_name"`
		MgrId        int    `json:"mgr_id"`
		MgrName      string `json:"mgr_name"`
		UserNickname string `json:"user_nickname"`
	}

	h.Type = 3
	err = fans_group2.SendToIm(ctx, h)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	b, _ := json.Marshal(DeleteContent{
		IsBackend:    req.AdminId > 0,
		AdminId:      int(req.AdminId),
		AdminName:    req.AdminName,
		MgrId:        int(req.MgrId),
		MgrName:      mgr.NickName,
		UserNickname: user.NickName,
	})
	h.Content = string(b)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	err = h.WriteMq()
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	// 删除单条消息 消息ID + 群ID
	err = fans_group2.DeleteSingleHistory(h, req.MsgId)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.DeleteMessageResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 撤回消息
func (s *TencentIM) RevokeMessage(ctx context.Context, req *pb.RevokeMessageReq) (resp *pb.RevokeMessageResp, err error) {
	resp = &pb.RevokeMessageResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	h, err := fans_group2.GetFromEs(req.MsgId)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	hcTime := time.Unix(h.SendTime, 0)
	if time.Now().Sub(hcTime).Minutes() > 5 {
		err = errors.New("消息超5分钟不可撤回")
		resp.Tips = err.Error()
		return
	}

	h.Type = 2
	err = fans_group2.SendToIm(ctx, h)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	err = h.WriteMq()
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	// 更新消息类型-撤回
	err = fans_group2.UpdateHistory(ctx, req.MsgId, map[string]interface{}{
		"type": 2,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.RevokeMessageResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 后台禁言用户
func (s *TencentIM) BanUser(ctx context.Context, req *pb.BanUserReq) (resp *pb.BanUserResp, err error) {
	resp = &pb.BanUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"group_id": req.GroupChatId,
		"user_id":  req.UserId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		err = fmt.Errorf("群成员id%d不存在", req.UserId)
		resp.Tips = err.Error()
		return
	}
	if gcUser.Role == models_main.GroupChatRoleAdmin || gcUser.Role == models_main.GroupChatRoleMaster {
		err = fmt.Errorf("群主/房管不能被禁言")
		resp.Tips = err.Error()
		return
	}

	mgr, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{
		"mgrid": req.UserId,
	})
	if mgr.Id > 0 {
		err = errors.New("房管不能被禁言")
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatBan(fans_group2.BanReq{
		AnchorId:       groupChat.AnchorId,
		FansGroupId:    groupChat.FansGroupId,
		BanUserId:      int(req.UserId),
		OperateUserId:  groupChat.AnchorId,
		DurationMinute: int(req.Duration),
		Reason:         req.Reason,
		BanType:        int(req.BanType),
		AdminId:        int(req.AdminId),
	}, "backend")
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	h := fans_group2.FansGroupHistory{
		Seq:      int64(snowflake.ID()),
		Uid:      int(req.UserId),
		GroupId:  gcUser.FansGroupId,
		NickName: "",
		Avatar:   "",
		Content:  "",
		SendTime: time.Now().Unix(),
		Type:     5,
		Role:     gcUser.Role,
	}
	err = h.WriteMq()
	if err != nil {
		global2.Log.Error(err)
	}

	err = fans_group2.SendToIm(ctx, &h)
	if err != nil {
		global2.Log.Error(err)
	}

	resp = &pb.BanUserResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 踢出群聊
func (s *TencentIM) KickUser(ctx context.Context, req *pb.KickUserReq) (resp *pb.KickUserResp, err error) {
	resp = &pb.KickUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUsers, err := db_main.GetGroupChatUserList(map[string]interface{}{
		"group_id": req.GroupChatId,
		"user_id": map[string]interface{}{
			"in": req.UserIds,
		},
	}, "", 0, 0)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if len(gcUsers) <= 0 {
		err = errors.New("群成员不存在")
		resp.Tips = err.Error()
		return
	}

	accountSlice := make([]string, len(gcUsers))
	gcUserMp := map[int]*models_main.GroupChatUser{}
	gcuIds := []int{}
	for i, v := range gcUsers {
		if v.Role == models_main.GroupChatRoleMaster {
			err = errors.New("不能踢出主播")
			resp.Tips = err.Error()
			return
		}
		accountSlice[i] = strconv.Itoa(v.UserId)
		gcUserMp[v.UserId] = gcUsers[i]
		gcuIds = append(gcuIds, v.Id)
	}

	ok := imsdk2.GetSdk().DeleteGroupMember(imsdk2.DeleteGroupMember{
		GroupID:            groupChat.FansGroupId,
		Silence:            1,
		MemberToDelAccount: accountSlice,
	})
	if !ok {
		err = errors.New("操作失败")
		resp.Tips = err.Error()
		return
	}

	err = db_main.DeleteGroupChatUsers(gcuIds)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	err = db_main.UpdateGroupChatsUserNum([]int{groupChat.Id})
	if err != nil {
		return
	}
	cache.DelFansGroup(groupChat.FansGroupId)

	for _, v := range req.UserIds {
		gcUser, ok := gcUserMp[int(v)]
		if !ok {
			continue
		}
		h := fans_group2.FansGroupHistory{
			Seq:      int64(snowflake.ID()),
			Uid:      int(v),
			GroupId:  groupChat.FansGroupId,
			NickName: "",
			Avatar:   "",
			Content:  "",
			SendTime: time.Now().Unix(),
			Type:     4,
			Role:     gcUser.Role,
		}
		err = h.WriteMq()
		if err != nil {
			global2.Log.Error(err)
		}
		err = fans_group2.SendToIm(ctx, &h)
		if err != nil {
			global2.Log.Error(err)
		}
		time.Sleep(time.Millisecond * 50)
	}

	resp = &pb.KickUserResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 群聊后台接口
func (s *TencentIM) SendGroupChatMsg(ctx context.Context, req *pb.SendGroupChatMsgReq) (resp *pb.SendGroupChatMsgResp, err error) {
	resp = &pb.SendGroupChatMsgResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupChatId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	anchor, err := mysql.GetUserParam(map[string]interface{}{
		"id": groupChat.AnchorId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if anchor.Id <= 0 {
		err = errors.New("主播不存在")
		resp.Tips = err.Error()
		return
	}

	hTyp := fans_messages.TextType
	if len(req.ImageUrl) > 0 {
		hTyp = fans_messages.ImageTextType
	}
	history, err := fans_group2.CustomReply{
		Uid:         groupChat.AnchorId,
		GroupId:     groupChat.FansGroupId,
		NickName:    anchor.NickName,
		Avatar:      anchor.Avatar,
		Content:     req.MsgContent,
		Type:        hTyp,
		Role:        2,
		ImageUrl:    req.ImageUrl,
		ImageWidth:  int(req.ImageWidth),
		ImageHeight: int(req.ImageHeight),
	}.SendToGroup(ctx)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.SendGroupChatMsgResp{
		IsSucceed: true,
		Tips:      "ok",
		MsgId:     cast.ToString(history.Seq),
	}
	return
}

// 后台解禁用户
func (s *TencentIM) CancelBanUser(ctx context.Context, req *pb.CancelBanUserReq) (resp *pb.CancelBanUserResp, err error) {
	resp = &pb.CancelBanUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.FansGroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatUnBan(fans_group2.BanReq{
		AnchorId:       groupChat.AnchorId,
		FansGroupId:    groupChat.FansGroupId,
		BanUserId:      int(req.BanUserId),
		OperateUserId:  int(req.OperateUserId),
		DurationMinute: 0,
		Reason:         "",
	}, "backend")
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.CancelBanUserResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

/**
==================================前端接口============================================================================
*/

// 主播详情页
func (s *TencentIM) GetAnchorProfile(ctx context.Context, req *pb.GetAnchorProfileReq) (resp *pb.GetAnchorProfileResp, err error) {
	resp = &pb.GetAnchorProfileResp{
		IsAttend:      0,
		AnchorProfile: &pb.AnchorProfile{},
		Groups:        []*pb.Group{},
	}

	anchor, err := mysql.GetUserParam(map[string]interface{}{"id": req.AnchorId})
	if err != nil {
		return
	}
	if anchor.Id <= 0 {
		err = errors.New("主播不存在")
		return
	}

	var level *api_models.Level
	level, err = services.GetUserLevel(anchor.Point)
	if err != nil {
		return
	}

	//获取关注信息
	attent, err := db_main.GetAnchorFansParam(map[string]interface{}{"fansid": req.UserId, "anchorid": req.AnchorId})
	if err == nil && attent.Id > 0 {
		resp.IsAttend = 1
	}

	//粉丝数量
	fansCount := cache.GetFansCount(int(req.AnchorId))

	//直播信息
	live, err := db_live.GetLiveParam(map[string]interface{}{"anchorid": req.AnchorId})
	if err != nil {
		global2.Log.Error(err)
	}

	categorys, err := cache.GetLiveCategory()
	if err != nil {
		global2.Log.Error(err)
	}
	category := &models_live.LiveCategory{}
	for _, v := range categorys {
		if v.Id == live.Categoryid {
			category = v
		}
	}

	//自我介绍
	auth, err := db_main.GetUserAuthParam(map[string]interface{}{"uid": req.AnchorId})
	if err != nil {
		global2.Log.Error(err)
	}

	resp.AnchorProfile = &pb.AnchorProfile{
		Id:           uint32(anchor.Id),
		Avatar:       anchor.Avatar,
		Name:         anchor.NickName,
		Introduce:    auth.Desc,
		HighHot:      int64(live.Hot),
		FansCount:    uint64(fansCount),
		CategoryId:   uint32(live.Categoryid),
		CategoryName: category.Title,
		UserLevel:    uint32(level.Level),
		LiveId:       uint64(live.Liveid),
	}

	//群组信息隐藏
	//groupChats, err := repository.GetGroupChatList(map[string]interface{}{
	//	"anchor_id": req.AnchorId,
	//}, "", 0, 0)
	//if err != nil {
	//	return
	//}
	//
	//gcUser, err := repository.GetGroupChatUserList(map[string]interface{}{
	//	"user_id": req.UserId,
	//}, "", 0, 0)
	//if err != nil {
	//	global.Log.Error(err)
	//}
	//gcUserMp := map[int]int{}
	//for _, v := range gcUser {
	//	gcUserMp[v.GroupId] = 1
	//}
	//
	//pbGroups := []*pb.Group{}
	//for _, v := range groupChats {
	//	_, ok := gcUserMp[v.Id]
	//	group := pb.Group{
	//		FansGroupId: v.FansGroupId,
	//		GroupId:     uint32(v.Id),
	//		Name:        v.Name,
	//		UserNum:     uint32(v.UserNum),
	//		LimitNum:    models.GroupChatLimitNum,
	//		IsJoined:    ok,
	//	}
	//	pbGroups = append(pbGroups, &group)
	//}
	//resp.Groups = pbGroups

	return
}

// 删除消息
func (s *TencentIM) FrontendDelMsg(ctx context.Context, req *pb.FrontendDelMsgReq) (resp *pb.DeleteMessageResp, err error) {
	resp = &pb.DeleteMessageResp{
		IsSucceed: false,
		Tips:      "",
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id": req.UserId,
		"role":    models_main.GroupChatRoleAdmin,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		mgr, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{
			"mgrid": req.UserId,
		})
		if mgr.Id <= 0 {
			err = errors.New("无权操作")
			resp.Tips = err.Error()
			return
		}
	}

	delMsgReq := &pb.DeleteMessageReq{
		GroupId: req.GroupId,
		MsgId:   req.MsgId,
		MgrId:   uint32(req.UserId),
	}
	return s.DeleteMessage(ctx, delMsgReq)
}

// 撤回消息
func (s *TencentIM) FrontendRevokeMsg(ctx context.Context, req *pb.FrontendRevokeMsgReq) (resp *pb.RevokeMessageResp, err error) {
	resp = &pb.RevokeMessageResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	rvkMsgReq := &pb.RevokeMessageReq{
		GroupId: req.GroupId,
		MsgId:   req.MsgId,
	}
	return s.RevokeMessage(ctx, rvkMsgReq)
}

// 前端禁言用户
func (s *TencentIM) FrontendBanUser(ctx context.Context, req *pb.FrontendBanUserReq) (resp *pb.BanUserResp, err error) {
	resp = &pb.BanUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	//前端多乘了60
	req.Duration = req.Duration / 60

	groupChat := cache.GetFansGroup(req.FansGroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id": req.OperateUserId,
		"role":    models_main.GroupChatRoleAdmin,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		mgr, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{
			"mgrid": req.OperateUserId,
		})
		if mgr.Id <= 0 {
			err = errors.New("无权操作")
			resp.Tips = err.Error()
			return
		}
	}

	gcUser, err = db_main.GetGroupChatUser(map[string]interface{}{
		"group_id": groupChat.Id,
		"user_id":  req.BanUserId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		err = fmt.Errorf("群成员id%d不存在", req.BanUserId)
		resp.Tips = err.Error()
		return
	}
	if gcUser.Role == models_main.GroupChatRoleAdmin || gcUser.Role == models_main.GroupChatRoleMaster {
		err = fmt.Errorf("群主/房管不能被禁言")
		resp.Tips = err.Error()
		return
	}

	mgr, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{
		"mgrid": req.BanUserId,
	})
	if mgr.Id > 0 {
		err = errors.New("房管不能被禁言")
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatBan(fans_group2.BanReq{
		AnchorId:       groupChat.AnchorId,
		FansGroupId:    groupChat.FansGroupId,
		BanUserId:      int(req.BanUserId),
		OperateUserId:  int(req.OperateUserId),
		DurationMinute: int(req.Duration),
		Reason:         req.Reason,
		BanType:        int(req.BanType),
	}, "frontend")
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	h := &fans_group2.FansGroupHistory{
		Seq:      int64(snowflake.ID()),
		Uid:      int(req.BanUserId),
		GroupId:  gcUser.FansGroupId,
		NickName: "",
		Avatar:   "",
		Content:  "",
		SendTime: time.Now().Unix(),
		Type:     5,
		Role:     gcUser.Role,
	}
	err = h.WriteMq()
	if err != nil {
		global2.Log.Error(err)
	}
	err = fans_group2.SendToIm(ctx, h)
	if err != nil {
		global2.Log.Error(err)
	}

	resp = &pb.BanUserResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 前端解禁用户
func (s *TencentIM) FrontendCancelBanUser(ctx context.Context, req *pb.FrontendCancelBanUserReq) (resp *pb.FrontendCancelBanUserResp, err error) {
	resp = &pb.FrontendCancelBanUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChat := cache.GetFansGroup(req.FansGroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id": req.BanUserId,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	err = fans_group2.SetGroupChatUnBan(fans_group2.BanReq{
		AnchorId:       groupChat.AnchorId,
		FansGroupId:    groupChat.FansGroupId,
		BanUserId:      int(req.BanUserId),
		OperateUserId:  int(req.OperateUserId),
		DurationMinute: 0,
		Reason:         "",
	}, "frontend")
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	h := fans_group2.FansGroupHistory{
		Seq:      int64(snowflake.ID()),
		Uid:      int(req.BanUserId),
		GroupId:  groupChat.FansGroupId,
		NickName: "",
		Avatar:   "",
		Content:  "",
		SendTime: time.Now().Unix(),
		Type:     6,
		Role:     gcUser.Role,
	}
	err = h.WriteMq()
	if err != nil {
		global2.Log.Error(err)
	}

	resp = &pb.FrontendCancelBanUserResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 房管踢人
func (s *TencentIM) FrontendKickUser(ctx context.Context, req *pb.FrontendKickUserReq) (resp *pb.KickUserResp, err error) {
	resp = &pb.KickUserResp{
		IsSucceed: false,
		Tips:      "",
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id": req.OperateUserId,
		"role":    models_main.GroupChatRoleAdmin,
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if gcUser.Id <= 0 {
		mgr, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{
			"mgrid": req.OperateUserId,
		})
		if mgr.Id <= 0 {
			err = errors.New("无权操作")
			return
		}
	}

	return s.KickUser(ctx, &pb.KickUserReq{
		UserIds:     req.KickUserIds,
		GroupChatId: req.GroupId,
	})
}

// 群聊页面
func (s *TencentIM) GetGroupInfo(ctx context.Context, req *pb.GetGroupInfoReq) (resp *pb.GetGroupInfoResp, err error) {
	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}

	gcUsers, err := db_main.GetGroupChatUserList(map[string]interface{}{
		"group_id": groupChat.Id,
	}, "role desc", 1, 6)

	userIds := []int{int(req.UserId)}
	for _, v := range gcUsers {
		userIds = append(userIds, v.UserId)
	}
	users, _ := db_main.GetUsersParam(map[string]interface{}{
		"id": map[string]interface{}{
			"in": userIds,
		},
	}, "", 0, 0)

	userMp := map[int]*models_main.User{}
	for k, v := range users {
		userMp[v.Id] = users[k]
	}

	banUsers, err := db_live.GetLiveRoomBannedusersParam(map[string]interface{}{
		"uid": map[string]interface{}{
			"in": append(userIds, int(req.UserId)),
		},
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"ban_time": map[string]interface{}{
			">": time.Now().Unix(),
		},
	})
	if err != nil {
		global2.Log.Error(err)
	}
	banUserMp := map[int]int{}
	for _, v := range banUsers {
		banUserMp[v.Uid] = 1
	}

	mgrs, err := db_live.GetLiveRoomManagersParam(map[string]interface{}{
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"mgrid": map[string]interface{}{
			"in": append(userIds, int(req.UserId)),
		},
	}, "", 0, 0)
	if err != nil {
		global2.Log.Error(err)
	}
	mgrMp := map[int]int{}
	for _, v := range mgrs {
		mgrMp[v.Mgrid] = 1
	}

	var members []*pb.GroupMember
	for _, v := range gcUsers {
		user, ok := userMp[v.UserId]
		_, isBan := banUserMp[v.UserId]
		_, isMgr := mgrMp[v.UserId]
		if isMgr && v.Role != models_main.GroupChatRoleMaster {
			v.Role = models_main.GroupChatRoleAdmin
		}
		if ok {
			members = append(members, &pb.GroupMember{
				Id:       uint32(v.UserId),
				NickName: user.NickName,
				Avatar:   user.Avatar,
				Role:     uint32(v.Role),
				IsBan:    isBan,
			})
		}
	}

	self, _ := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id":  req.UserId,
		"group_id": req.GroupId,
	})
	selfUser, ok := userMp[int(req.UserId)]
	if !ok {
		selfUser = &models_main.User{}
	}
	_, isBan := banUserMp[int(req.UserId)]
	_, isMgr := mgrMp[int(req.UserId)]
	if isMgr && self.Role != models_main.GroupChatRoleMaster {
		self.Role = models_main.GroupChatRoleAdmin
	}

	resp = &pb.GetGroupInfoResp{
		Id:        uint32(groupChat.Id),
		Name:      groupChat.Name,
		Avatar:    groupChat.Avatar,
		Introduce: groupChat.Introduce,
		UserNum:   uint32(groupChat.UserNum),
		LimitNum:  models_main.GroupChatLimitNum,
		Members:   members,
		UserInfo: &pb.SelfMember{
			Id:       uint32(selfUser.Id),
			NickName: selfUser.NickName,
			Avatar:   selfUser.Avatar,
			Role:     uint32(self.Role),
			IsBan:    isBan,
			IsJoined: self.Id > 0,
		},
		FansGroupId: groupChat.FansGroupId,
	}

	return
}

// 清空历史
func (s *TencentIM) ClearHistory(ctx context.Context, req *pb.ClearHistoryReq) (resp *pb.OperateSucceedResp, err error) {
	resp = &pb.OperateSucceedResp{}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}

	gcDel := &models_main.GroupChatDelete{
		CreateStamp: time.Now().Unix(),
		UserId:      int(req.UserId),
		GroupId:     int(req.GroupId),
		FansGroupId: groupChat.FansGroupId,
	}
	err = db_main.InsertGroupChatDelete(gcDel)
	if err != nil {
		return
	}

	resp.IsSucceed = true
	return
}

// 清空并退出
func (s *TencentIM) ClearAndQuit(ctx context.Context, req *pb.ClearAndQuitReq) (resp *pb.OperateSucceedResp, err error) {
	resp = &pb.OperateSucceedResp{}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"group_id": req.GroupId,
		"user_id":  req.UserId,
	})
	if err != nil {
		return
	}
	if gcUser.Role == models_main.GroupChatRoleMaster {
		err = errors.New("操作失败")
		return
	}
	err = db_main.DeleteGroupChatUser(gcUser)
	if err != nil {
		return
	}

	err = db_main.UpdateGroupChatsUserNum([]int{groupChat.Id})
	if err != nil {
		return
	}
	cache.DelFansGroup(groupChat.Id)

	ok := imsdk2.GetSdk().DeleteGroupMember(imsdk2.DeleteGroupMember{
		GroupID:            groupChat.FansGroupId,
		Silence:            1,
		MemberToDelAccount: []string{cast.ToString(gcUser.UserId)},
	})
	if !ok {
		err = errors.New("操作失败")
		return
	}

	return s.ClearHistory(ctx, &pb.ClearHistoryReq{
		GroupId: req.GroupId,
		UserId:  req.UserId,
	})
}

// 获取群成员
func (s *TencentIM) GetGroupMembers(ctx context.Context, req *pb.GetGroupMembersReq) (resp *pb.GetGroupMembersResp, err error) {
	resp = &pb.GetGroupMembersResp{}

	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}

	gcUsers, err := db_main.GetGroupChatUserJoinList(map[string]interface{}{
		"group_id": req.GroupId,
	}, "role desc", 0, 0)

	userIds := []int{int(req.UserId)}
	userMp := map[int]*models_main.User{}
	for _, v := range gcUsers {
		userIds = append(userIds, v.UserId)
	}

	users, _ := db_main.GetUsersParam(map[string]interface{}{
		"id": map[string]interface{}{
			"in": userIds,
		},
	}, "", 0, 0)
	for k, v := range users {
		userMp[v.Id] = users[k]
	}

	banUsers, err := db_live.GetLiveRoomBannedusersParam(map[string]interface{}{
		"uid": map[string]interface{}{
			"in": append(userIds, int(req.UserId)),
		},
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"ban_time": map[string]interface{}{
			">": time.Now().Unix(),
		},
	})
	if err != nil {
		global2.Log.Error(err)
	}
	banUserMp := map[int]int{}
	for _, v := range banUsers {
		banUserMp[v.Uid] = 1
	}

	mgrs, err := db_live.GetLiveRoomManagersParam(map[string]interface{}{
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"mgrid": map[string]interface{}{
			"in": append(userIds, int(req.UserId)),
		},
	}, "", 0, 0)
	if err != nil {
		global2.Log.Error(err)
	}
	mgrMp := map[int]int{}
	for _, v := range mgrs {
		mgrMp[v.Mgrid] = 1
	}

	var members []*pb.GroupMember
	for _, v := range gcUsers {
		user, ok := userMp[v.UserId]
		if ok {
			_, isBan := banUserMp[v.UserId]
			_, isMgr := mgrMp[v.UserId]
			if isMgr && v.Role != models_main.GroupChatRoleMaster {
				v.Role = models_main.GroupChatRoleAdmin
			}
			members = append(members, &pb.GroupMember{
				Id:       uint32(v.UserId),
				NickName: user.NickName,
				Avatar:   user.Avatar,
				Role:     uint32(v.Role),
				IsBan:    isBan,
			})
		}
	}

	self, _ := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id":  req.UserId,
		"group_id": req.GroupId,
	})
	selfUser, ok := userMp[int(req.UserId)]
	if !ok {
		selfUser = &models_main.User{}
	}
	_, isBan := banUserMp[int(req.UserId)]
	_, isMgr := mgrMp[int(req.UserId)]
	if isMgr && self.Role != models_main.GroupChatRoleMaster {
		self.Role = models_main.ReplyRoleAdmin
	}

	resp = &pb.GetGroupMembersResp{
		Members: members,
		UserInfo: &pb.SelfMember{
			Id:       uint32(selfUser.Id),
			NickName: selfUser.NickName,
			Avatar:   selfUser.Avatar,
			Role:     uint32(self.Role),
			IsJoined: self.Id > 0,
			IsBan:    isBan,
		},
	}
	return
}

// 加入群组
func (s *TencentIM) AddToGroupChat(ctx context.Context, req *pb.AddToGroupChatReq) (resp *pb.AddToGroupChatResp, err error) {
	resp = &pb.AddToGroupChatResp{
		IsSucceed: false,
		Tips:      "",
	}
	groupChat := cache.GetFansGroup(req.GroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		resp.Tips = err.Error()
		return
	}

	if groupChat.UserNum >= models_main.GroupChatLimitNum {
		err = errors.New("群人数已满")
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id":  req.UserId,
		"group_id": groupChat.Id,
	})
	if err != nil {
		return
	}
	if gcUser.Id > 0 {
		err = errors.New("用户已加入群组")
		return
	}

	gcUser = &models_main.GroupChatUser{
		CreatedAt:   time.Now(),
		GroupId:     groupChat.Id,
		FansGroupId: groupChat.FansGroupId,
		UserId:      int(req.UserId),
		Role:        models_main.GroupChatRoleMember,
		Status:      models_main.GroupChatUserStatusCommon,
	}

	//直播间房管同步
	managerUser, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": req.UserId})
	if managerUser.Id > 0 && (managerUser.Anchorid == groupChat.AnchorId || managerUser.Anchorid == 0) {
		gcUser.Role = models_main.GroupChatRoleAdmin
	}

	ok, _ := imsdk2.GetSdk().AddGroupMember(imsdk2.AddGroupMemberRequest{
		GroupId: groupChat.FansGroupId,
		Silence: 1,
		MemberList: []imsdk2.MemberList{
			{
				MemberAccount: cast.ToString(gcUser.UserId),
			},
		},
	})
	if !ok {
		resp.Tips = "添加成员失败"
		return resp, status.Error(codes.Internal, "添加成员失败")
	}

	err = db_main.InsertGroupChatUser(gcUser)
	if err != nil {
		return
	}

	err = db_main.UpdateGroupChatsUserNum([]int{groupChat.Id})
	if err != nil {
		return
	}
	cache.DelFansGroup(groupChat.FansGroupId)

	u, err := mysql.GetUserParam(map[string]interface{}{
		"id": req.UserId,
	})
	if err != nil {
		global2.Log.Error(err)
	}
	_, err = fans_group2.CustomReply{
		Uid:      int(req.UserId),
		GroupId:  groupChat.FansGroupId,
		NickName: u.NickName,
		Avatar:   "",
		Content:  "",
		Type:     fans_messages.JoinType,
		Role:     0,
	}.SendToGroup(ctx)
	if err != nil {
		global2.Log.Error(err)
	}

	resp = &pb.AddToGroupChatResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 聊天列表
func (s *TencentIM) GetGroupList(ctx context.Context, req *pb.GetGroupListReq) (resp *pb.GetGroupListResp, err error) {
	groupList := []*pb.GroupList{}
	resp = &pb.GetGroupListResp{GroupList: groupList}

	var gcUsers []*models_main.GroupChatUser
	gcUsers, err = db_main.GetGroupChatUserList(map[string]interface{}{
		"user_id": req.UserId,
	}, "", 0, 0)
	if err != nil {
		return
	}

	if len(gcUsers) <= 0 {
		return
	}

	groupIds := []int{}
	for _, v := range gcUsers {
		groupIds = append(groupIds, v.GroupId)
	}
	if len(groupIds) <= 0 {
		return
	}

	var groups []*models_main.GroupChat
	groups, err = db_main.GetGroupChatList(map[string]interface{}{
		"id": map[string]interface{}{
			"in": groupIds,
		},
	}, "", 0, 0)
	if err != nil {
		return nil, err
	}

	//查询当前用户清空消息的记录
	gcDels, err := db_main.GetGroupChatDeleteList(map[string]interface{}{
		"user_id": req.UserId,
	}, "", 0, 0)
	if err != nil {
		global2.Log.Error(err)
	}
	gcDelMp := map[string]int64{}
	if len(gcDels) > 0 {
		for _, v := range gcDels {
			gcDel, ok := gcDelMp[v.FansGroupId]
			if ok && gcDel > v.CreateStamp {
				gcDelMp[v.FansGroupId] = v.CreateStamp
				continue
			}
			gcDelMp[v.FansGroupId] = v.CreateStamp
		}
	}

	type SortGroup struct {
		*pb.GroupList
		LatestMsgStamp int64
	}

	SortGroupList := []SortGroup{}
	for _, v := range groups {
		unreadNum := cache.GetGroupUserUnreadMsgNum(cast.ToString(req.UserId), v.FansGroupId)
		isOnline := false
		live, _ := cache.GetAnchorLive(v.AnchorId)
		if live != nil {
			isOnline = live.IsLive()
		}

		latestMsg := cache.GetGroupChatLatestMsg(v.FansGroupId)
		gcDelStamp, _ := gcDelMp[v.FansGroupId]
		if latestMsg.LatestMsgTime > 0 &&
			gcDelStamp > 0 &&
			gcDelStamp >= latestMsg.LatestMsgTime {
			continue
		}

		SortGroupList = append(SortGroupList, SortGroup{
			GroupList: &pb.GroupList{
				Avatar:      v.Avatar,
				Name:        v.Name,
				UserNum:     uint32(v.UserNum),
				UnreadNum:   uint32(unreadNum),
				AnchorId:    uint32(v.AnchorId),
				Id:          uint32(v.Id),
				FansGroupId: v.FansGroupId,
				IsOnline:    isOnline,
			},
			LatestMsgStamp: latestMsg.LatestMsgTime,
		})
	}
	sort.Slice(SortGroupList, func(i, j int) bool {
		return SortGroupList[i].LatestMsgStamp > SortGroupList[j].LatestMsgStamp
	})

	copier.Copy(&groupList, &SortGroupList)
	resp = &pb.GetGroupListResp{GroupList: groupList}
	return
}

// 获取聊天历史
func (s *TencentIM) GetFansGroupHistory(ctx context.Context, req *pb.FansGroupHistoryRequest) (*pb.FansGroupHistoryResponse, error) {
	history, total := fans_group2.QueryByUserHistory(req.GroupId, int(req.UserId), int(req.Page), int(req.Limit))
	if len(history) == 0 {
		return &pb.FansGroupHistoryResponse{}, nil
	}
	records := make([]*pb.FansGroupHistory, 0)
	err := copier.Copy(&records, &history)
	if err != nil {
		return nil, status.Errorf(codes.Internal, fmt.Errorf("history error: %v", err).Error())
	}
	resp := &pb.FansGroupHistoryResponse{
		FansGroupHistory: records,
		Total:            total,
	}

	return resp, nil
}

// 取消关注退出群组
func (s *TencentIM) QuitGroupAfterUnsubscribe(ctx context.Context, req *pb.QuitGroupAfterUnsubscribeReq) (resp *pb.QuitGroupAfterUnsubscribeResp, err error) {
	resp = &pb.QuitGroupAfterUnsubscribeResp{
		IsSucceed: false,
		Tips:      "",
	}

	groupChats, err := db_main.GetGroupChatList(map[string]interface{}{
		"anchor_id": req.AnchorId,
	}, "", 0, 0)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	if len(groupChats) <= 0 {
		resp.IsSucceed = true
		return
	}

	groupIds := []int{}
	groupMp := map[int]*models_main.GroupChat{}
	for k, v := range groupChats {
		groupIds = append(groupIds, v.Id)
		groupMp[v.Id] = groupChats[k]
	}
	gcUsers, err := db_main.GetGroupChatUserList(map[string]interface{}{
		"group_id": map[string]interface{}{
			"in": groupIds,
		},
		"user_id": req.UserId,
	}, "", 0, 0)

	if len(gcUsers) <= 0 {
		resp.IsSucceed = true
		return
	}

	gcUserIds := []int{}
	for _, v := range gcUsers {
		gcUserIds = append(gcUserIds, v.Id)
		groupChat, ok := groupMp[v.GroupId]
		if ok {
			imsdk2.GetSdk().DeleteGroupMember(imsdk2.DeleteGroupMember{
				GroupID:            groupChat.FansGroupId,
				Silence:            1,
				MemberToDelAccount: []string{cast.ToString(v.UserId)},
			})
		}
	}
	err = db_main.DeleteGroupChatUsers(gcUserIds)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	err = db_main.UpdateGroupChatsUserNum(groupIds)
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	for _, v := range groupIds {
		cache.DelFansGroup(v)
	}

	resp = &pb.QuitGroupAfterUnsubscribeResp{
		IsSucceed: true,
		Tips:      "ok",
	}
	return
}

// 获取禁言信息
func (s *TencentIM) GetBanInfo(ctx context.Context, req *pb.GetBanInfoReq) (resp *pb.GetBanInfoResp, err error) {
	groupChat := cache.GetFansGroup(req.FansGroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}
	oBanned, _ := db_live.GetLiveRoomBanneduserParam(map[string]interface{}{
		"uid": req.UserId,
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"ban_time": map[string]interface{}{
			">": time.Now().Unix(),
		},
	})

	// 目标用户信息
	user, err := mysql.GetUserParam(map[string]interface{}{"id": req.UserId})
	if err != nil {
		return
	}

	var level *api_models.Level
	level, err = services.GetUserLevel(user.Point)
	if err != nil {
		return
	}

	// 贵族
	var record *api_models.NobleRecordRes
	record, err = db_main.GetNobleRecordByUid(int(req.UserId))
	if err != nil {
		return
	}

	resp = &pb.GetBanInfoResp{
		IsBan:        oBanned.Id != 0,
		UserName:     user.NickName,
		Avatar:       user.Avatar,
		UserLevel:    int32(level.Level),
		UserVipTitle: int32(record.NobleId),
		Reason:       oBanned.Reason,
		DurationDesc: time2.Time2Msg(oBanned.BanTime - time.Now().Unix()),
	}
	return
}
